import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import LayoutView from '@/views/LayoutView.vue'
import LoginView from '@/views/LoginView.vue'
import PageError from '@/views/PageError.vue'
import { useUserStore } from '@/stores/UserStore'
import RouterMap from '@/router/RouterMap'
let initBool: boolean = true
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'main',
      component: LayoutView,
      //   beforeEnter: (to, from, next) => {
      //     const store = useUserStore()
      //     RouterMap.forEach((item: RouteRecordRaw) => {
      //       if (store.userInfo.routes.includes(item.path)) {
      //         router.addRoute('main', item)
      //       }
      //     })
      //     next()
      //   },
    },
    {
      path: '/login',
      name: 'login',
      meta: { nologin: true },
      component: LoginView,
    },
    {
      path: '/:pathMatch(.*)',
      name: 'error',
      component: PageError,
    },
  ],
})

router.beforeEach((to, from, next) => {
  const store = useUserStore()
  if (!to.meta.nologin) {
    if (!store.token) {
      next({ name: 'login' })
      return
    }
  }else{
    next()
    return
  }
  if (initBool) {
    initBool = false
    RouterMap.forEach((item: RouteRecordRaw) => {
      if (store.userInfo.routes.includes(item.path)) {
        console.log(store.userInfo)
        router.addRoute('main', item)
      }
    })
    console.log(router.getRoutes())
    // if (to.path === '/') {
    //   // 这里可以直接用 store.userInfo.routes[0] 或者菜单 mock 数据
      
    //   next({ path: store.userInfo.routes[0] })
    //   console.log(store.userInfo.routes[0])
    //   return
    // }
    next({ path: to.path })

    return
  }
  next()
})
export default router
